package com.example.demo.scheduledtask;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.example.demo.common.Constant;
import com.example.demo.config.ErpConfig;
import com.example.demo.mapper.AsyncWorkorderMapper;
import com.example.demo.mapper.PoMpsinfoMapper;
import com.example.demo.mapper.WmsPurchaseMapper;
import com.example.demo.utils.SoapXmlUtil;
import com.example.demo.vo.AsyncWorkorderVo;
import com.example.demo.vo.ReturnInReceiptListVo;
import com.example.demo.vo.ReturnInVo;
import com.example.demo.vo.XmlResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : Zhang.yt
 * @date : 2024/7/29
 */
@Component
@Slf4j
@DS("wms")
public class ReturnInCallback {
    @Resource
    private WmsPurchaseMapper wmsPurchaseMapper;

    @Autowired
    private SoapXmlUtil soapXmlUtil;

    @Autowired
    PoMpsinfoMapper poMpsinfoMapper;

    @Resource
    private ErpConfig erpConfig;

    @Resource
    private AsyncWorkorderMapper asyncWorkorderMapper;
    /**
     * 生产工单（退料单）
     */
    @Scheduled(fixedDelay = 21 * 1000)//开启定时同步
    //@Async(value = "taskExecutor")
    public void returnInCallback() {
        //查询没有回调的数据
        ReturnInVo returnInVo = wmsPurchaseMapper.getReturnInCallback();
//        List<String> innoList = returnInCallback.stream().map(ReturnInVo::getSfda014).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(returnInVo)) {
            log.info("未查询到生产工单（退料单）数据，修改失败单据重新回写");
            wmsPurchaseMapper.returnInCallbackLose();
            return;
        }
        //根据没有回调的数据查询细表
        List<ReturnInReceiptListVo> returnInReceiptListVos = wmsPurchaseMapper.getReturnInReceiptListCallback(returnInVo.getSfda014());
//        Map<String, List<ReturnInReceiptListVo>> listMap = returnInReceiptList.stream().collect(Collectors.groupingBy(ReturnInReceiptListVo::getInno));
//        for (ReturnInVo returnInVo : returnInCallback) {
        try {
            returnInVo.setActionType(Constant.ActionType_I);
            returnInVo.setSfdadocno(Constant.PMDSDOCNO_5430);
            returnInVo.setSfdasite(Constant.PMDSSITE_AMA);
//            List<ReturnInReceiptListVo> returnInReceiptListVos = listMap.get(returnInVo.getSfda014());

            //获取生产工单可用的项次和相序，退料后ERP会在生产工单备料明细扣减已发数量，后续可以继续领料，我们这边走生产补料，不限制数量，补料需要回填ERP
            List<ReturnInReceiptListVo> returnInReceiptListVoReqs = assembleMorderAutoidAndSequence(returnInReceiptListVos, returnInVo.getSfda014());
            if (CollUtil.isEmpty(returnInReceiptListVoReqs)) {
                wmsPurchaseMapper.updateReBackMaterialCallback(returnInVo.getSfda014(), "计算工单项次异常请联系开发人员处理", 2);
            }
//                List<ReturnInReceiptListVoReq> returnInReceiptListVoReqs = BeanUtil.copyToList(returnInReceiptListVos, ReturnInReceiptListVoReq.class);
            String resMessage = soapXmlUtil.getSoapXml("ReBackMaterial", "sfda_t", "sfdc_t", returnInVo, returnInReceiptListVoReqs);

            //转换为soap消息
            log.info("生产退料回调:{}", resMessage);

            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("soap接口生产退料回调->{}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateReBackMaterialCallback(returnInVo.getSfda014(), xmlResp.getData().get("sfdadocno"), 1);
                //更新erp工单发料信息
                asyncWorkorderMapper.updateAsyncWorkorder(returnInReceiptListVoReqs.get(0).getSfdc001());
                //更新wms工单发料信息
                for (ReturnInReceiptListVo returnInReceiptListVo : returnInReceiptListVos) {
                    asyncWorkorderMapper.updateWmsPoLead(returnInReceiptListVo);
                }

            } else {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateReBackMaterialCallback(returnInVo.getSfda014(), xmlResp.getMessage(), 2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            wmsPurchaseMapper.updateReBackMaterialCallback(returnInVo.getSfda014(), "非常见的数据处理问题，请联系开发人员处理", 2);
        }
//        }
    }

    private List<ReturnInReceiptListVo> assembleMorderAutoidAndSequence(List<ReturnInReceiptListVo> returnInReceiptListVos, String sfda014) {
        List<ReturnInReceiptListVo> reqList = new ArrayList<>();
        for (ReturnInReceiptListVo returnInReceiptListVo : returnInReceiptListVos) {
            List<AsyncWorkorderVo> asyncWorkorderVos = wmsPurchaseMapper.getWOrkOrderReq(returnInReceiptListVo);
            if (CollUtil.isNotEmpty(asyncWorkorderVos)) {
                BigDecimal sfdc007 = returnInReceiptListVo.getSfdc007();
                for (AsyncWorkorderVo asyncWorkorderVo : asyncWorkorderVos) {
                    ReturnInReceiptListVo copiedProperties = BeanUtil.copyProperties(returnInReceiptListVo, ReturnInReceiptListVo.class);
                    copiedProperties.setSfdc002(asyncWorkorderVo.getItem());
                    copiedProperties.setSfdc003(asyncWorkorderVo.getTerm());
                    //数量大于等于发出数量
                    if (sfdc007.compareTo(asyncWorkorderVo.getNum()) >= 0) {
                        copiedProperties.setSfdc007(sfdc007);
                        sfdc007 = sfdc007.subtract(asyncWorkorderVo.getNum());
                    } else {
                        copiedProperties.setSfdc007(sfdc007);
                        sfdc007 = BigDecimal.ZERO;
                    }
                    reqList.add(copiedProperties);
                    if (sfdc007.compareTo(BigDecimal.ZERO) == 0) {
                        break;
                    }
                }
            }
        }
        return reqList;
    }
}
